package com.tuotu.gps;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.tuotu.gps.entity.LocationInfo;
import com.tuotu.gps.entity.MessageEvent;
import com.tuotu.gps.utils.HttpNetworkUtil;
import com.tuotu.gps.utils.Preference;
import com.tuotu.gps.utils.Utils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

public class UploadService extends Service implements HttpNetworkUtil.onResultListener {
    private final IBinder binder = new MyBinder();
    Vector<LocationInfo> vectors=new Vector<>();
//    Vector<File> pathVector=new Vector<>();
    HttpNetworkUtil mHttpNetworkUtil;
    SharedPreferences userPreferences;
    String userId;
    OnResultListener OnResultListener;
    public static volatile boolean isUploading;

    public interface OnResultListener{
        void onQueryResult(Vector<LocationInfo> vectors);
        void onSuccessResult(LocationInfo locationInfo);
        void onFailResult(LocationInfo locationInfo);
    }

    public void setOnResultListener(UploadService.OnResultListener onResultListener) {
        OnResultListener = onResultListener;
    }

    @Override
    public IBinder onBind(Intent intent) {
        Log.e("xyww","UploadService onBind");
        return binder;
    }

    public Vector<LocationInfo> getVectors() {
        return vectors;
    }

    @Override
    public void onSuccess(String s, String path) {

    }

    @Override
    public void onError(String path) {

    }

    @Override
    public void onSuccessInfo(String s, LocationInfo locationInfo) {
        vectors.remove(locationInfo);
        OnResultListener.onSuccessResult(locationInfo);
        moveFile(locationInfo,RecordActivity2.GPS_UPLOAD_DIR+"success");
    }

    @Override
    public void onFailInfo(LocationInfo locationInfo) {
        vectors.remove(locationInfo);
        OnResultListener.onFailResult(locationInfo);
        moveFile(locationInfo,RecordActivity2.GPS_UPLOAD_DIR+"fail");
    }

    private void moveFile(LocationInfo locationInfo,String path){
        try {
            File file1=new File(locationInfo.getMp3PathName());
            File file2=new File(locationInfo.getTxtPathName());
            Utils.MoveFolderAndFileWithSelf(file1.getPath(), path);
            Utils.MoveFolderAndFileWithSelf(file2.getPath(), path);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public class MyBinder extends Binder {
        UploadService getService() {
            return UploadService.this;
        }
    }

    public boolean isUploading() {
        return isUploading;
    }

    public void setUploading(boolean uploading) {
        isUploading = uploading;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("xyww","UploadService onCreate");
        userPreferences=getSharedPreferences(Preference.User.PREFERENCE_USER, Context.MODE_PRIVATE);
        userId= userPreferences.getString(Preference.User.PREFERENCE_USER_NAME,"13631505080");
        mHttpNetworkUtil=new HttpNetworkUtil();
        mHttpNetworkUtil.setOnResultListener(this);
    }


    public void queryUploadFile(String path,boolean needUpload) {
//        queryFile(isUploadAll?RecordActivity.GPS_DIR:RecordActivity2.GPS_UPLOAD_DIR+"fail/");
        Log.e("xyww","queryUploadFile  isUploading===="+isUploading);
        if(isUploading && null!=vectors && vectors.size()>0){
                OnResultListener.onQueryResult(vectors);
                Log.e("xyww","queryUploadFile  vectors 1===="+vectors.size());
        }else {

            if(needUpload){
                isUploading=true;

            queryFile(path);

            Iterator<LocationInfo> iterator=vectors.iterator();

                Log.e("xyww","queryUploadFile  vectors 2===="+vectors.size());
                if(null!=vectors && vectors.size()>0) {
                    OnResultListener.onQueryResult(vectors);
                }

                while (iterator.hasNext()){
                    mHttpNetworkUtil.httpPostMp3AndTxt(this,userId,iterator.next());
                }
            }
        }

        EventBus.getDefault().post(MessageEvent.MSG_UPLOAD_FILE_DONE);
    }

    private void queryFile(String path){
        File file = new File(path);
        if (file.length()>0){
            File[] files = file.listFiles();
            if(null==files){
                return;
            }
            for (File file1:files) {
                if (file1.isDirectory()){
                    queryFile(file1.getPath());
                }else{

                    String tmpName = file1.getPath();//获取全名,如fire.mp3
                    int index = tmpName.lastIndexOf(".");//"."最后出现的位置
                    String ext = tmpName.substring(index+1).toLowerCase();//文件类型名s获取
                    String name=file1.getPath().substring(0,index);
                    if (file1.length() <= 0) {
                        Utils.deleteFile(name);
                        continue;
                    }
                    if(ext.contains("mp3")){
                        LocationInfo li=new LocationInfo();
                        li.setMp3PathName(file1.getPath());
                        li.setMp3Name(file1.getName());
                        li.setTxtPathName(name+".txt");
                        vectors.add(li);
                    }
//                    else if(file1.getName().contains("-") && ext.contains("txt")){
//                        pathVector.add(file1);
//                    }
                }

            }
        }
    }


    @Override
    public void onDestroy() {
        // 当调用者退出(即使没有调用unbindService)或者主动停止服务时会调用
        super.onDestroy();
        Log.e("xyww","UploadService onDestroy");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // 当调用者退出(即使没有调用unbindService)或者主动停止服务时会调用
        Log.e("xyww","UploadService onUnbind");
        return super.onUnbind(intent);
    }
}
